//
//  ErWeiMaPage.m
//  MarketManager
//
//  Created by 翟荣升 on 2017/6/9.
//  Copyright © 2017年 finedo. All rights reserved.
//
#import "UIHelper.h"
#import "ErWeiMaPage.h"
#import <AVFoundation/AVFoundation.h>
#import "UIView+zq_extension.h"
#import "ZQQrResultPage.h"
/**
 *  屏幕 高 宽 边界
 */
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define SCREEN_BOUNDS  [UIScreen mainScreen].bounds

#define MaxHeight   CGRectGetMinY(self.bottomImageView.frame) + self.bottomImageView.zq_height / 2 - CGRectGetMaxY(self.topImageView.frame) + self.topImageView.zq_height / 2


#define QrImgBoundWidth 272
#define QrImgBoundHeght 30

#define QrBoundWidth 269
#define QrBoundHeght 307
#define TOP (SCREEN_HEIGHT-240)/2
#define LEFT (SCREEN_WIDTH-269)/2
#define BackButton CGRectMake((SCREEN_WIDTH - 112)/2, SCREEN_HEIGHT - 150, 112, 112)
#define kScanRect CGRectMake(LEFT, TOP, 269, 270)
//#define kScanRect CGRectMake(LEFT, TOP, 220, 220)
@interface ErWeiMaPage ()<AVCaptureMetadataOutputObjectsDelegate>{
    
    BOOL fromTopToBottom;
    NSTimer * timer;
    CAShapeLayer *cropLayer;
}
/**  */
@property (nonatomic, assign) int LineY;
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;

@property (nonatomic, weak) UIImageView * line;
/**  */
@property (nonatomic, weak) UIImageView *topImageView;
@property (nonatomic, weak) UIImageView *bottomImageView;

/** label */
@property (nonatomic, weak) UILabel *describeTopLabel;
@end

@implementation ErWeiMaPage

- (UIImageView *)line
{
    if (!_line) {
        UIImageView *line = [[UIImageView alloc] init];
        [self.view addSubview:line];
        _line = line;
    }
    return _line;
}


- (UILabel *)describeTopLabel
{
    if (!_describeTopLabel) {
        UILabel *describeTopLabel = [[UILabel alloc] init];
        [self.view addSubview:describeTopLabel];
        _describeTopLabel = describeTopLabel;
    }
    return _describeTopLabel;
}

- (UIImageView *)topImageView
{
    if (!_topImageView) {
       UIImageView *topImageView = [[UIImageView alloc] init];
        _topImageView = topImageView;
    }
    return _topImageView;
}

- (UIImageView *)bottomImageView
{
    if (!_bottomImageView) {
        UIImageView *bottomImageView = [[UIImageView alloc] init];
        _bottomImageView = bottomImageView;
    }
    return _bottomImageView;
}


- (void)viewWillAppear:(BOOL)animated{
//    self.navigationController.navigationBarHidden=NO;
    [self setCropRect:kScanRect];
    [self configView];
    [self performSelector:@selector(setupCamera) withObject:nil afterDelay:0.3];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"扫描冷钱包";
    self.view.backgroundColor = [UIColor blackColor];
}


- (void)configView{
    UIImageView * imageViewTop = [[UIImageView alloc]init];
    imageViewTop.zq_width = 272;
    imageViewTop.zq_height = QrImgBoundHeght;
    imageViewTop.center = self.view.center;
    imageViewTop.zq_y = self.view.zq_centerY - (QrBoundHeght / 2 - QrImgBoundHeght);
    imageViewTop.zq_x = self.view.zq_centerX - (QrImgBoundWidth / 2);
    imageViewTop.image = [UIImage imageNamed:@"qr_top"];
    self.topImageView = imageViewTop;
    [self.view addSubview:imageViewTop];
    
    UIImageView * imageViewBottom = [[UIImageView alloc]init];
    imageViewBottom.zq_width = 272;
    imageViewBottom.zq_height = QrImgBoundHeght;
    imageViewBottom.center = self.view.center;
    imageViewBottom.zq_y = self.view.zq_centerY + (QrBoundHeght / 2 - QrImgBoundHeght);
    imageViewBottom.zq_x = self.view.zq_centerX - (QrImgBoundWidth / 2);
    imageViewBottom.image = [UIImage imageNamed:@"qr_bottom"];
    self.bottomImageView = imageViewBottom;
    [self.view addSubview:imageViewBottom];
    self.view.backgroundColor=[UIColor blackColor];
    NSLog(@"imageViewTop == %@",NSStringFromCGRect(imageViewTop.frame));
   

    self.describeTopLabel.zq_size = CGSizeMake(300, 21);
    self.describeTopLabel.font = [UIFont systemFontOfSize:14];
    self.describeTopLabel.textColor = [UIColor whiteColor];
    self.describeTopLabel.text = @"请扫描冷钱包获取广播信息";
    self.describeTopLabel.textAlignment = NSTextAlignmentCenter;
    self.describeTopLabel.center = imageViewTop.center;
    self.describeTopLabel.zq_y = imageViewTop.zq_y - 60;
    fromTopToBottom = YES;
 
    self.line.frame = imageViewTop.frame;
    self.line.zq_width = QrBoundWidth;
    self.line.zq_height = 2;
    self.line.zq_y = CGRectGetMaxY(self.topImageView.frame) - self.topImageView.zq_height / 2;
    self.line.backgroundColor = [UIColor stringToColor:@"#999999"];
//    _line.image = [UIImage imageNamed:@"line.png"];
    [self.view addSubview:_line];
    

    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    
}

- (void)animation1
{
//    NSLog(@"num == %d", self.LineY);
    if (fromTopToBottom == YES) {
         self.LineY ++;
        self.line.zq_y += 2;
        
        CGFloat maxHeight = CGRectGetMinY(self.bottomImageView.frame) + self.bottomImageView.zq_height / 2 - CGRectGetMaxY(self.topImageView.frame) + self.topImageView.zq_height / 2;
        NSLog(@"self.LineY%d=====%f",self.LineY,MaxHeight);
        if (self.LineY == maxHeight / 2) {
            fromTopToBottom = NO;
        }
    }
    else {
       self.LineY --;
        _line.zq_y -= 2 ;
        if (self.LineY <= 0) {
            fromTopToBottom = YES;
        }
    }
    
}


- (void)setCropRect:(CGRect)cropRect{
    cropLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, cropRect);
    CGPathAddRect(path, nil, self.view.bounds);
    
    [cropLayer setFillRule:kCAFillRuleEvenOdd];
    [cropLayer setPath:path];
    [cropLayer setFillColor:[UIColor blackColor].CGColor];
    [cropLayer setOpacity:0.6];
    [cropLayer setNeedsDisplay];
    
    [self.view.layer addSublayer:cropLayer];

}

- (void)setupCamera
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device==nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //设置扫描区域
    CGFloat top = TOP/SCREEN_HEIGHT;
    CGFloat left = LEFT/SCREEN_WIDTH;
    CGFloat width = QrBoundWidth/SCREEN_WIDTH;
    CGFloat height = QrBoundHeght/SCREEN_HEIGHT;
    ///top 与 left 互换  width 与 height 互换
    [_output setRectOfInterest:CGRectMake(top,left, height, width)];
    
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    [_output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode, nil]];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    // Start
    [_session startRunning];
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        //停止扫描
        [_session stopRunning];
        [timer setFireDate:[NSDate distantFuture]];
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
  
        if ([self.flag isEqualToString:@"rightItem"]) {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = stringValue;
            [UIHelper showSuccessMessage:@"复制成功" afterHideHud:2 toView:self.view completion:^{
                [self.navigationController popViewControllerAnimated:YES];
                return;
            }];
        } else {
            if (stringValue.length  == 0) {
                [UIHelper showMessage:@"扫码失败，请重试" toView:self.view];
            }else{
                ZQQrResultPage *vc = [ZQQrResultPage new];
                vc.zzModel = self.zzModel;
                vc.penModel = self.penModel;
                vc.resultContent = stringValue;
                [self.navigationController pushViewController:vc animated:YES];
                NSLog(@"扫描结果：%@",stringValue);
            }
        }
        
    } else {
        [UIHelper showTipsWithText:@"无扫描信息" inView:self.view];
        return;
    }
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [timer invalidate];
    timer = nil;
    self.LineY = 0;
//    [self.line removeFromSuperview];
    self.view=[[UIView alloc]initWithFrame:self.view.bounds];
}

@end
